package com.wyl.mine.userinfo

import android.content.Intent
import android.view.View
import androidx.lifecycle.Observer
import com.bumptech.glide.Glide
import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import com.luck.picture.lib.config.PictureMimeType
import com.luck.picture.lib.tools.PictureFileUtils
import com.wuhenzhizao.titlebar.widget.CommonTitleBar
import com.wyl.base.COMPRESS_SIZE
import com.wyl.base.userData
import com.wyl.libbase.base.BindingActivity
import com.wyl.libbase.utils.KLog
import com.wyl.libbase.extend.toast
import com.wyl.mine.R
import com.wyl.mine.databinding.UserInfoActivityBinding
import org.koin.android.viewmodel.ext.android.viewModel
import java.io.File

const val NAME = 2
const val PHONE = 3

class UserInfoActivity : BindingActivity<UserInfoActivityBinding>() {
    private val viewModel: UserInfoViewModel by viewModel()

    override fun getLayoutId(): Int = R.layout.user_info_activity

    override fun initView() {
        binding.vm = viewModel

        binding.titlebar.setListener { _, action, _ ->
            when (action) {
                CommonTitleBar.ACTION_LEFT_BUTTON -> onBackPressed()
                else -> {
                }
            }
        }

        binding.radioGroup.setOnCheckedChangeListener { group, id ->
            when (id) {
                R.id.radiobutton1 -> viewModel.updateInfo(sex = "1")
                R.id.radiobutton2 -> viewModel.updateInfo(sex = "2")
                else -> {
                }
            }
        }
    }

    override fun loadData() {
        userData?.let {
            viewModel.mUserData.set(it)
            binding.radioGroup.check(
                if (it.sex == "1") R.id.radiobutton1 else R.id.radiobutton2
            )
        }

        viewModel.success.observe(this, Observer {
            toast(it)
        })

        viewModel.error.observe(this, Observer {
            toast(it)
        })
    }

    override fun onClick(v: View) {
        when (v.id) {
            R.id.layout_name -> openEditActivity()
            R.id.head_img_layout -> selectePhoto()
            R.id.change_phone_layout ->
                startActivityForResult(Intent(this, EditPhoneActivity::class.java), PHONE)
            else -> {
            }
        }
    }

    private fun openEditActivity() {
        startActivityForResult(
            Intent(this, EditActivity::class.java)
                .putExtra("title", "修改昵称")
                .putExtra("mUserData", viewModel.mUserData.get()?.name),
            NAME
        )
    }

    private fun selectePhoto() {
        PictureSelector.create(this)
            .openGallery(PictureMimeType.ofImage())
            .selectionMode(PictureConfig.SINGLE)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
//            .maxSelectNum(1)// 最大图片选择数量
            .enableCrop(true)// 是否裁剪 true or false
            .withAspectRatio(1, 1)// int 裁剪比例 如16:9 3:2 3:4 1:1 可自定义
            .freeStyleCropEnabled(false)// 裁剪框是否可拖拽 true or false
            .rotateEnabled(false) // 裁剪是否可旋转图片 true or false
            .scaleEnabled(true)// 裁剪是否可放大缩小图片 true or false
            .circleDimmedLayer(true)// 是否圆形裁剪 true or false
            .showCropFrame(false)// 是否显示裁剪矩形边框 圆形裁剪时建议设为false   true or false
            .showCropGrid(false)// 是否显示裁剪矩形网格 圆形裁剪时建议设为false    true or false
            .compress(true)// 是否压缩
            .glideOverride(160, 160)// glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
            .minimumCompressSize(COMPRESS_SIZE)// 压缩图片大小
            .forResult(PictureConfig.CHOOSE_REQUEST)
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode != RESULT_OK) return
        if (requestCode == NAME) {
            data?.apply {
                val name = this.extras["content"] as String
                viewModel.updateInfo(name = name)
            }
            return
        }
        if (requestCode == PHONE) {
            data?.apply {
                val phone = this.extras["content"] as String
                viewModel.updateInfo(phone = phone)
            }
            return
        }
        if (requestCode == PictureConfig.CHOOSE_REQUEST) {
            // 图片选择结果回调
            val list = PictureSelector.obtainMultipleResult(data)
            val media = list[0]
            // 例如 LocalMedia 里面返回三种path
            // 1.media.getPath(); 为原图path
            // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
            // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
            // 如果裁剪并压缩了，已取压缩路径为准，因为是先裁剪后压缩的
            val path = when {
                media.isCompressed -> media.compressPath
                media.isCut -> media.cutPath
                else -> media.path
            }
            KLog.d("path = $path, media.isCompressed  =${media.isCompressed}, media.isCut  =${media.isCut}")
            Glide.with(this).load(path).into(binding.headImg)
            viewModel.updatePic(File(path))
            return
        }
    }

    override fun onDestroy() {
        PictureFileUtils.deleteCacheDirFile(this)
        super.onDestroy()
    }

}
